<template>
    <el-dialog v-model="visible" :width="width" :title="title" @closed="resetForm" @open="init" :close-on-press-escape="false">
        <el-form :inline="true"
                 label-width="100px"
                 label-position="left"
                 label-suffix="："
                 :model="dept"
                 :rules="rules" ref="formRef">
            <el-form-item label="编号" prop="id" style="display: none">
                <el-input v-model="dept.id"/>
            </el-form-item>
            <el-form-item label="公司名称" prop="companyId">
                <el-select v-model="dept.companyId" clearable filterable placeholder="请选择所属公司">
                    <el-option :label="item.name" :value="item.id" v-for="(item,index) in $store.state.companyOptions"/>
                </el-select>
            </el-form-item>
            <el-form-item label="上级部门" prop="parentId">
                <el-select v-model="dept.parentId" filterable clearable placeholder="选择上级部门">
                    <template v-for="(item,index) in deptOptions">
                        <el-option :label="item.deptName" :value="item.id" v-if="item.id!==dept.id"></el-option>
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item label="部门名称" class="full-item" prop="deptName">
                <el-input placeholder="请输入部门名称" v-model="dept.deptName"/>
            </el-form-item>
            <el-form-item label="部门负责人" prop="principalName">
                <el-input v-model="dept.principalName" disabled/>
            </el-form-item>

            <el-form-item label="状态" prop="enabled">
                <el-radio-group v-model="dept.enabled">
                    <el-radio :label="1">正常</el-radio>
                    <el-radio :label="0">停用</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="所在地址" class="full-item" prop="address">
                <el-input placeholder="请输入部门所在地址" v-model="dept.address"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="default" @click="visible=false">取消</el-button>
            <template v-if="type===0">
                <el-button type="primary" @click="submitAdd">确认添加</el-button>
            </template>
            <template v-else>
                <el-button type="primary" @click="submitUpdate">确认修改</el-button>
            </template>
        </template>
    </el-dialog>
</template>

<script>
import {addDept, hasSomeDeptName, updateDept} from "../../../../network/sys/dept";
import {getCompanyOptions} from "../../../../network/sys/company";
import {getDeptList} from "../../../../network/sys/dept";
import {ref, reactive, getCurrentInstance, toRefs} from "vue";
import {ElMessage} from "element-plus";

    export default {
        name: "DeptForm",
        emits:['refresh-data'],
        setup(props,{emit}){
            const globalProperties = getCurrentInstance()?.appContext.config.globalProperties;
            const visible = ref(false)
            const formRef = ref(null);
            const validateDeptName = async (rule,value,callback)=>{
                await hasSomeDeptName({
                    id: form.dept.id,
                    deptName: form.dept.deptName,
                    companyId: form.dept.companyId
                }).then(vo=>{
                    if(vo){//同公司下存在其他相同名称的部门
                        callback(new Error('该公司已有相同名称的部门'))
                    }
                })
                callback();
            }
            const form = reactive({
                dept:{
                    id: null,
                    companyId: null,
                    deptName: null,
                    address: null,
                    parentId: null,
                    principalName:null,
                    enabled: 1,
                },
                rules:{
                    deptName: [
                        {required: true,message: '请输入部门名称',trigger: 'blur'},
                        {validator: validateDeptName, trigger: 'blur'}
                    ],
                    address: [
                        {required: true,message: '请输入部门地址',trigger: 'blur'},
                    ],
                    companyId:[
                        {required: true,message: '请选择部门所属公司',trigger: 'blur'},
                    ]
                },
                resetForm: ()=>{
                    formRef.value.resetFields();
                    formRef.value.clearValidate();
                },
                submitAdd: ()=>{
                    formRef.value.validate((valid)=>{
                        if(valid){
                            addDept(form.dept).then(vo=>{
                                globalProperties.$response.handle({
                                    data:vo,
                                    success: '添加成功',
                                    error: '添加失败',
                                    successFn: ()=>{
                                        emit('refresh-data');
                                        visible.value = false;
                                    }
                                })
                            })
                        }else{
                            ElMessage.error('请先完善表单项！')
                        }
                    })
                },
                submitUpdate(){
                    formRef.value.validate((valid)=>{
                        if(valid){
                            updateDept(form.dept).then(vo=>{
                                globalProperties.$response.handle({
                                    data:vo,
                                    success: '修改成功',
                                    error: '修改失败',
                                    successFn: ()=>{
                                        emit('refresh-data');
                                        visible.value = false;
                                    }
                                })
                            })
                        }else{
                            ElMessage.error('请先完善表单项！')
                        }
                    })
                },
                setDept: ({id, companyId, deptName, address, parentId, principalName, enabled})=>{
                    form.dept.id = id;
                    form.dept.companyId = companyId;
                    form.dept.deptName = deptName;
                    form.dept.address = address;
                    form.dept.parentId = parentId;
                    form.dept.principalName = principalName;
                    form.dept.enabled = enabled;
                }
            })
            return{
                ...toRefs(form),
                formRef,
                visible
            }
        },
        props:{
            width: '',
        },
        data(){
            return{
                deptOptions: [
                    {
                        id: null
                    }
                ],
                title: null,
                type: 0,
                options:[],
            }
        },
        methods:{
            loadCompanyOptions(){
                getCompanyOptions().then(vo=>{
                    this.$store.commit('setCompanyOptions',vo.data);
                    // console.log('加载公司选项数据：',vo)
                })
            },
            init(){
                if(this.$store.state.companyOptions.length===0){
                    this.loadCompanyOptions();
                }
            }
        },
        created() {
            this.init();
        },
        watch:{
            "dept.companyId"(newVal,oldVal){
                this.dept.parentId = null;
                getDeptList(newVal).then(vo=>{
                    // console.log('部门数据：',vo);
                    this.deptOptions = vo.data;
                })
            }
        }
    }
</script>

<style scoped>
    .full-item {
        width: 666px;
    }
</style>
<style>
.el-select-dropdown{
    width: 200px;
}
.el-select-dropdown__item{
    width: 100%;
}
</style>
